package com.pactera.controller;

import com.pactera.error.BizException;
import com.pactera.error.EmBizError;
import com.pactera.response.CommonReturnType;
import com.pactera.constant.Constant;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonReturnType doError(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        ex.printStackTrace();
        Map<String, Object> responseData = new HashMap<>();
        if (ex instanceof BizException) {
            BizException bizException = (BizException) ex;
            responseData.put("errorCode", bizException.getErrorCode());
            responseData.put("errorMsg", bizException.getErrorMessage());
            // url参数是必传
        } else if (ex instanceof ServletRequestBindingException) {
            responseData.put("errorCode", EmBizError.UNKNOW_ERROR.getErrorCode());
            responseData.put("errorMsg", Constant.URL_ROUTER_BINDING_PROBLEM);
            //
        } else if (ex instanceof NoHandlerFoundException) {
            responseData.put("errorCode", EmBizError.UNKNOW_ERROR.getErrorCode());
            responseData.put("errorMsg", Constant.NOT_FOUND_VISIT_PATH);
        } else {
            responseData.put("errorCode", EmBizError.UNKNOW_ERROR.getErrorCode());
            responseData.put("errorMsg", EmBizError.UNKNOW_ERROR.getErrorMessage());
        }
        return CommonReturnType.create(responseData, Constant.FAIL);
    }
}
